package com.atguigu.gulimall.gulimallsearch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.gulimall.gulimallsearch.config.EsConfig;
import com.atguigu.gulimall.gulimallsearch.service.esService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class esServiceImpl implements esService {

    @Resource
    RestHighLevelClient restHighLevelClient;


    @Override
    public Boolean saveModel(List<SkuEsModel> skuEsModelList) throws IOException {



        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            //常量
            IndexRequest request = new IndexRequest("product");
            //设置ID
            request.id(skuEsModel.getSkuId().toString());
            //设置内容
            String res = JSONObject.toJSONString(skuEsModel);
            request.source(res, XContentType.JSON);
            bulkRequest.add(request);

        }

        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        boolean flag = bulkResponse.hasFailures();

        if (!flag){
            List<String> collect = Arrays.stream(bulkResponse.getItems()).map(bulkItemResponse -> {
                return bulkItemResponse.getId();
            }).collect(Collectors.toList());
            log.error("商品上架成功：{}",collect);
        }
        return flag;
    }

}
